import ddddocr
import requests
import base64


def get_user_token():
    url = 'https://testapi.hnilab.com/api/Login/Login'
    json_data = {
        "account": "17839068212",
        "password": "2020womenxiangyu",
    }
    key_code = get_verify_code()
    json_data.update(key_code)
    res = requests.post(url, json=json_data)
    if res.status_code == 200:
        if res.json()["code"] == 200:
            # print(res.json()['rows']['accesstoken'])
            return res.json()['rows']['accesstoken']
        else:
            print(res.json())
    else:
        print(res.status_code)


def get_user_info():
    token = get_user_token()
    headers = {
        "Authorization": f"Bearer {token}"
    }
    url = 'https://testapi.hnilab.com/api/User/GetTokenUser'

    res = requests.get(url=url, headers=headers)
    if res.status_code == 200:
        # print(res.json()["rows"]["username"])
        return res.json()["rows"]["username"]
    else:
        print(res.status_code)


def image_to_code(image_path):
    ocr = ddddocr.DdddOcr(show_ad=False)
    with open("../datas/code/code.jpg", "rb") as f:
        result = ocr.classification(f.read())
        return result


# result = image_to_code()
# print(result)


def get_verify_code():
    url = 'https://testapi.hnilab.com/api/Login/GenerateVerifyCode'
    res = requests.get(url)
    res = res.json()["rows"]
    key = res["key"]
    codeimage = res['codeimage'][22:]
    codeimage = base64.b64decode(codeimage)
    image_path = f"../datas/code/code.jpg"
    with open(f"../datas/code/code.jpg", "wb") as f:
        f.write(codeimage)
    code = image_to_code(image_path)
    return {
        "verifycode": code,
        "key": key
    }


print(get_user_info())
